package kr.hkit.androidcomplete02.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import kr.hkit.androidcomplete02.R;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ApacheDownHtml extends Activity {
	ProgressDialog mProgress;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Button btn = (Button) findViewById(R.id.down);
		btn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				mProgress = ProgressDialog.show(ApacheDownHtml.this, "Wait", "Downloading...");
				DownThread thread = new DownThread(
						"http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=2714055500");
				thread.start();
			}
		});
	}
	
	class DownThread extends Thread{
		String mAddr;
		
		DownThread(String addr) {
			mAddr = addr;
		}
		
		@Override
		public void run() {
			HttpGet get = new HttpGet(mAddr);
			DefaultHttpClient client = new DefaultHttpClient();
			try {
				client.execute(get, mResHandler);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	ResponseHandler<String> mResHandler = new ResponseHandler<String>() {

		@Override
		public String handleResponse(HttpResponse response)
				throws ClientProtocolException, IOException {
		StringBuilder html = new StringBuilder();
		try{
		BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		for(;;){
			String line = br.readLine();
			if(line == null) break;
			html.append(line + '\n');
		}
		br.close();

		Message message = mAfterDown.obtainMessage();
		message.obj = html.toString();
		mAfterDown.sendMessage(message);
		}catch(Exception e){;}
		return html.toString();
		}
	};
	
	Handler mAfterDown = new Handler(){
		public void handleMessage(Message msg){
			mProgress.dismiss();
			TextView result = (TextView) findViewById(R.id.resulthtml);
			result.setText((String)msg.obj);
		}
	};
}
